import torch

tensor_uninitialized = torch.empty(4, 3)
print("未初始化的张量：\n", tensor_uninitialized)

tensor_random = torch.rand(4, 3)
print("随机初始化的张量：\n", tensor_random)

tensor_zeros = torch.zeros(4, 3, dtype=torch.int)
print("全为0的张量：\n", tensor_zeros)

tensor_data = torch.tensor([6.7, 4.2])
print("使用数据创建的张量：\n", tensor_data)

other_tensor = torch.rand(4, 3)

addition_result1 = tensor_random + other_tensor
addition_result2 = torch.add(tensor_random, other_tensor)
print("张量加法 (方法1)：\n", addition_result1)
print("张量加法 (方法2)：\n", addition_result2)

indexed_tensor = tensor_random[:, 2]
print("张量索引：\n", indexed_tensor)

original_tensor = torch.randn(3, 5)
flattened_tensor = original_tensor.view(15)
reshaped_tensor = original_tensor.view(-1, 5)
print("改变形状前：\n", original_tensor.size())
print("改变形状后 (flattened_tensor)：\n", flattened_tensor.size())
print("改变形状后 (reshaped_tensor)：\n", reshaped_tensor.size())

weight = torch.tensor([2.0], requires_grad=True)
bias = torch.tensor([1.0], requires_grad=True)
input_tensor = torch.tensor([4.0])

output = weight * input_tensor + bias

output.backward()

print("weight的梯度 (doutput/dweight)：\n", weight.grad)
print("bias的梯度 (doutput/dbias)：\n", bias.grad)
